package org.wlldTest.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Test {
    public static void main(String[] args) throws Exception {
        test();
    }

    public static void test() throws Exception {
        //预处理
        List<MyPosition> positionList = new ArrayList<>();
        Random random = new Random();
        NormSort normSort = new NormSort();
        for (int i = 1; i < 1001; i++) {//假数据
            float x = random.nextInt(1000) / 1000f;//归一化（-1,1）
            float y = random.nextInt(1000) / 1000f;//归一化
            float norm = (float) Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));//范数
            MyPosition myPosition = new MyPosition();
            myPosition.setX(x);
            myPosition.setY(y);
            myPosition.setId(i);
            myPosition.setNorm(norm);
            positionList.add(myPosition);
        }
        //归一化 value 归一化后  (value-minValue)/(maxValue-minValue) (0,1)
        positionList.sort(normSort);//根据norm排序
        LineRegion lineRegion = new LineRegion(positionList.size());
        for (int i = 0; i < positionList.size(); i++) {
            MyPosition myPosition = positionList.get(i);
            float e = i / 1000f;
            myPosition.setUid(i);
            lineRegion.insertPosition(myPosition.getX(), myPosition.getY(), e);
        }
        lineRegion.start();//回归
        //实际匹配坐标
        float rx = random.nextInt(1000) / 1000f;//归一化（-1,1）
        float ry = random.nextInt(1000) / 1000f;//归一化
        System.out.println("测试目标点X:" + (rx * 1000D) + ",目标点Y：" + (ry * 1000D));
        int index = (int) (lineRegion.getIndex(rx, ry) * 1000D);//还原
        MyPosition myPosition = getMyPosition(positionList, index);
        System.out.println("匹配点X:" + (myPosition.getX() * 1000D) + ",匹配点Y:" + (myPosition.getY() * 1000D));
        getBest(positionList, rx, ry);
    }

    private static void getBest(List<MyPosition> positionList, float x, float y) {
        float minDist = 10000;
        int index = 0;
        for (int i = 0; i < positionList.size(); i++) {
            MyPosition myPosition = positionList.get(i);
            float dist = (float) Math.sqrt(Math.pow(myPosition.getX() - x, 2) + Math.pow(myPosition.getY() - y, 2));
            if (dist < minDist) {
                index = i;
                minDist = dist;
            }
        }
        MyPosition myPosition = positionList.get(index);
        System.out.println("最近匹配点X:" + (myPosition.getX() * 1000D) + ",匹配点Y:" + (myPosition.getY() * 1000D));
    }

    private static MyPosition getMyPosition(List<MyPosition> positionList, int uid) {
        MyPosition myPosition = null;
        for (MyPosition position : positionList) {
            if (position.getUid() == uid) {
                myPosition = position;
                break;
            }
        }
        return myPosition;
    }
}
